﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace OmniKits.Windows.Behaviors
{
    public class SelectAllOnFocusBehavior : Behavior<TextBoxBase>
    {
        private TextBoxBase _TextBoxBase;

        protected override void OnAttached()
        {
            _TextBoxBase = this.AssociatedObject;

            _TextBoxBase.GotKeyboardFocus += OnGotFocus;
            _TextBoxBase.PreviewMouseDown += OnMouseDown;
        }

        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (_TextBoxBase.IsFocused) return;

            if (Keyboard.Focus(_TextBoxBase) == _TextBoxBase)
                e.Handled = true;
        }

        private void OnGotFocus(object sender, RoutedEventArgs e)
        {
            _TextBoxBase.SelectAll();
        }

        protected override void OnDetaching()
        {
            _TextBoxBase.GotKeyboardFocus -= OnGotFocus;
            _TextBoxBase.PreviewMouseDown -= OnMouseDown;

            _TextBoxBase = null;
        }
    }
}
